package com.appnet.android.truyencuoi;

import java.io.IOException;
import java.util.ArrayList;

import com.appnet.android.truyencuoi.db.DataBaseHelper;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

public class MainActivity extends Activity {

	private static final String TAG = ComicConstant.PRE_TAG + MainActivity.class.getSimpleName();
	
	private ArrayList<ItemComic> mItems;
	private ListView mLvCategories;
	private ListViewAdapter mAdapter;
	private ProgressDialog mDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mDialog = new ProgressDialog(this);
		mDialog.setMessage(getResources().getString(R.string.pre_loading_data));
		mDialog.setCancelable(false);
		mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mDialog.show();
		new CreatingDb().execute();
	}
	
	class CreatingDb extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			
			DataBaseHelper mDbHelper = new DataBaseHelper(getApplicationContext());
			try {
				mDbHelper.createDataBase();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			mLvCategories = (ListView) findViewById(R.id.lv_categories);
			//
			String[] values = getResources().getStringArray(R.array.value_categories);
			String[] keys = getResources().getStringArray(R.array.key_categories);
			int size = values.length;
			mItems = new ArrayList<ItemComic>(size);
			for(int i = 0; i < size; i++) {
				mItems.add(new ItemComic(Integer.valueOf(keys[i]), values[i]));
			}
			
			mAdapter = new ListViewAdapter(getApplicationContext(), mItems, new ItemOnClick() {
				
				@Override
				public void onClick(int type, int value) {
					Log.d(TAG, "onclick: type: " + type + " value: " + value);
					Intent intent = new Intent(getApplicationContext(), ListStoryActivity.class);
					intent.putExtra(ComicConstant.EXTRA_CATEGORY, value);
					startActivity(intent);
				}
			}, 1);
			
			mLvCategories.setAdapter(mAdapter);
			mDialog.dismiss();
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
